package org.example.xsda.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * SaToken 配置
 */
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {

    /**
     * 注册 SaToken 拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/api/auth/login",
                        "/api/auth/register",
                        "/favicon.ico",
                        "/error"
                );
    }

    /**
     * 权限认证接口实现
     */
    @Bean
    public StpInterface stpInterface() {
        return new StpInterface() {
            @Override
            public List<String> getPermissionList(Object loginId, String loginType) {
                // 返回此 loginId 拥有的权限列表
                List<String> permissionList = new ArrayList<>();
                // 这里可以从数据库查询用户权限
                return permissionList;
            }

            @Override
            public List<String> getRoleList(Object loginId, String loginType) {
                // 返回此 loginId 拥有的角色列表
                List<String> roleList = new ArrayList<>();
                // 这里可以从数据库查询用户角色
                Object roleCode = StpUtil.getSession().get("roleCode");
                if (roleCode != null) {
                    roleList.add(roleCode.toString());
                }
                return roleList;
            }
        };
    }
}

